package org.example.Rw;

import java.util.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class readWriteLock {
    public static void main(String[] args) {
        myCacheLock myCache = new myCacheLock();
        // 写入
        for (int i = 1; i <= 5; i++) {
            final int p = i;
            new Thread(()->{
                myCache.put(p+"",p+"");
            },String.valueOf(i)).start();
        }

        // 读取
        for (int i = 1; i <= 5; i++) {
            final int p = i;
            new Thread(()->{
                myCache.get(p+"");
            },String.valueOf(i)).start();
        }

    }
}


/**
 * 加了读写锁
 */

class myCacheLock{
    private volatile Map<String,Object> map = new HashMap<>();

    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    // 存入
    public void put(String key , Object value){
            readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"写入" + key);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }

    }

    // 读取
    public void get(String key){
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"读取" + key);
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
}


/**
 * 未加ReadwriteLock
 */
class myCache{
    private volatile Map<String,Object> map = new HashMap<>();

    // 存入
    public void put(String key , Object value){
        System.out.println(Thread.currentThread().getName()+"写入" + key);
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"写入OK");
    }

    // 读取
    public void get(String key){
        System.out.println(Thread.currentThread().getName()+"读取" + key);
        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName()+"读取OK");
    }
}



